// CSV.cpp: implementation of the CSV class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "CSV.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

int CsvParser::SplitLine(string& str)
{
    m_sLine = str;
    m_vsField.clear();
    return Split();
}

string CsvParser::GetField(int n)
{
    if (n < 0 || n >= (int)m_vsField.size())
        return "";
    else
        return m_vsField[n];
}

int CsvParser::GetNumberOfFields()
{
    return m_nField;
}

int CsvParser::Split()
{
    m_nField = 0;
	
    int line_length = m_sLine.length();
    if (line_length == 0)
        return 0;
	
    string field;
	
    int cur_pos = 0;
    int next_pos = 0;
    do {
        // skip spaces
        for (; m_sLine[cur_pos]==' '; cur_pos++);
        
        if (m_sLine[cur_pos] == '"')  
            next_pos = ExtractStringField(m_sLine, field, cur_pos);
        else
            next_pos = ExtractNumericField(m_sLine, field, cur_pos);
		
        m_vsField.push_back(field);
        m_nField++;
		
        cur_pos = next_pos + 1; // skip current ',' and start looking for the next
		
    } while (cur_pos < line_length);
	
    return m_nField;
	
}

int CsvParser::ExtractStringField(string& source, string& field, int start_pos)
{
    field = "";
	
    int cur_pos = 0;
    int line_length = source.length();
	
    start_pos++;   // skip first '"'
	
    // find next '"'
    cur_pos = source.find_first_of("\"", start_pos);
    if (cur_pos < 0 )
    {
        cur_pos = line_length;
    }
	
    field = string(source, start_pos, cur_pos-start_pos);
	
    // find next ','
    cur_pos = source.find_first_of(m_sFieldSep, cur_pos);
    if (cur_pos < 0 )
    {
        cur_pos = line_length;
    }
	
    return cur_pos;
}


int CsvParser::ExtractNumericField(string& source, string& field, int start_pos)
{
    field = "";
	
    int cur_pos = 0;
    int line_length = source.length();
    
    // find first ','
    cur_pos = source.find_first_of(m_sFieldSep, start_pos);
    if (cur_pos < 0 )
    {
        cur_pos = line_length;
    }
    
    field = string(source, start_pos, cur_pos-start_pos);
	
    return cur_pos;
} 